﻿using KTD.Web.Models;
using KTD.Web.Models.VD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XXS.Common.BaseDataAccessLayer;
using XXS.Common.Paginate;

namespace KTD.Web.BLL
{
    public class DicManager
    {

        private readonly IBaseDAL<Dic> _DicDal;
        public DicManager()
        {
            _DicDal = new BaseDAL<Dic>(new DB());
        }

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="im"></param>
        /// <returns></returns>
        public virtual IPaginate<DicVD> GetListBy(DicQD im)
        {
            var res = _DicDal.FindList();
            if (!string.IsNullOrEmpty(im.Query))
            {
                res = res.Where(n => n.Value.Contains(im.Query));
            }
            if (im.DicType!=null)
            {
                res = res.Where(n => n.DicType==im.DicType);
            }
            var list = res.OrderBy(n => n.DicType).ThenBy(n => n.Order)
                .ToPaginate(im, n => new DicVD().MapFrom(n));
            return list;
        }

        /// <summary>
        /// 新建字典
        /// </summary>
        /// <param name="im"></param>
        public void Create(DicCUD im)
        {
            Dic model = new Dic();
            im.MapTo(model);
            _DicDal.Create(model);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="im"></param>
        public void Update(DicCUD im)
        {
            Dic model = _DicDal.Find(im.Id);
            im.MapTo(model);
            _DicDal.Update(model);
        }
        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DicCUD Find(int id)
        {
            Dic model = _DicDal.Find(id);
            return new DicCUD().MapFrom(model);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            Dic model = _DicDal.Find(id);
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            _DicDal.Delete(model);
        }
    }
}